<template>
  <div class="fillcontain" style="padding: 25px 15px 15px;">
    <div style="display:flex; height: 700px;">
      <asstnt-stndrd-items @queryStandItemTableData="queryStandItemTableData" ref="projectLibrary"
        itmeRootName="standItem" @editOrDeleteAction="editOrDeleteAction" @stndrdItemDelete="stndrdItemDelete">
        <template slot="btn-slot">
          <el-button type="danger" size="mini" style="margin: 12px 20px 0;" plain icon="el-icon-circle-plus-outline"
            @click="addProject">标准化
          </el-button>
        </template>
      </asstnt-stndrd-items>
      <div class="right_box">
        <div class="right-title">标准化属性</div>
        <!-- 标准化属性列表 -->
        <div style="margin-left:40px ;">
          <!-- 新增按钮 -->
          <el-button type="danger" plain style="margin: 10px;" @click="sonAddClick"
            :disabled="currentRow.isLock">新增</el-button>
          <el-button type="danger" @click="standPropertySaveClick" :disabled="currentRow.isLock">保存</el-button>
          <el-table :data="tableData" style="width: 100%" height="250px" ref="table" highlight-current-row>
            <el-table-column align="center" type="index" min-width="80" label="序号"></el-table-column>
            <el-table-column label="属性分类" min-width="100" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.propertyType" placeholder="请选择" filterable clearable
                  :disabled="currentRow.isLock" @change="(val)=>propertyTypeClk(val,scope.row)">
                  <el-option v-for="item in propertyTypeOpt" :key="item.id + ''" :label="item.label"
                    :value="item.value + ''">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="属性" min-width="150" align="center">
              <template slot-scope="scope">
                <el-select v-if="scope.row.propertyType == '1'" v-model="scope.row.propertyId" placeholder="请选择通用属性"
                  filterable clearable :disabled="currentRow.isLock">
                  <el-option v-for="item in propertyListOpt" :key="item.id + ''" :label="item.propertyName"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-input v-else-if="scope.row.propertyType == '0'" v-model="scope.row.propertyName"
                  placeholder="请输入自定义属性" maxlength="50" :disabled="currentRow.isLock"></el-input>
                <el-input v-else v-model="propertyTypeCheck" placeholder="请选择属性分类" maxlength="50" disabled></el-input>
              </template>
            </el-table-column>
            <el-table-column label="关键字设置" min-width="150" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.exampleInfo" placeholder="请输入" maxlength="50"
                  :disabled="currentRow.isLock"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="体检分级标志" min-width="80" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.gradedFlag" placeholder="请选择" filterable clearable
                  :disabled="currentRow.isLock || scope.row.propertyType == '0' ">
                  <el-option v-for="item in gradedFlagOpt" :key="item.id + ''" :label="item.label"
                    :value="item.value + ''">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="75" align="center">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)"
                  :disabled="currentRow.isLock"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="right-title" style="margin-top: 15px;">个人健康属性</div>
        <!-- 个人健康属性 -->
        <div style="margin-left:40px ;">
          <!-- 新增按钮 -->
          <el-button type="danger" plain style="margin: 10px;" @click="healthAddClick"
            :disabled="currentRow.isLock">新增</el-button>
          <el-button type="danger" @click="healthPropertySaveClick" :disabled="currentRow.isLock">保存</el-button>
          <el-table :data="tableData2" style="width: 100%" height="250px" ref="table" highlight-current-row>
            <el-table-column align="center" type="index" min-width="80" label="序号"></el-table-column>
            <el-table-column label="个人健康信息" min-width="250" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.propertyName" placeholder="请输入" maxlength="50"
                  :disabled="currentRow.isLock"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="移动端是否显示" min-width="60" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.showFlag" placeholder="请选择" filterable clearable
                  :disabled="currentRow.isLock">
                  <el-option v-for="item in mobileShowFlag" :key="item.id + ''" :label="item.label"
                    :value="item.value + ''">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="75" align="center">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-delete" @click="healthHandleDel(scope.$index, scope.row)"
                  :disabled="currentRow.isLock"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <el-dialog :title="titleInfo" :visible.sync="addProjectVisible" v-if="addProjectVisible" :show-close="false"
      :close-on-click-modal="false" width="35%" center>
      <el-form ref="stndrdItemForm" :model="stndrdItemForm" label-width="100px" :rules="projectRules"
        style="overflow: hidden;">
        <el-row>
          <el-col :span="20" class="common-box">
            <el-form-item label="项目代码：" prop="itemsCode">
              <el-input :disabled="itemCodeFlag" v-model="stndrdItemForm.itemsCode" placeholder="项目代码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20" class="common-box">
            <el-form-item label="项目名称：" prop="itemsName">
              <el-input v-model="stndrdItemForm.itemsName" placeholder="项目名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="stndrdItemSave">保 存</el-button>
        <el-button @click="projectReset">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAusAsstntHealthPropertyInfoApi, saveAusAsstntHealthPropertyInfoApi, delAusAsstntHealthPropertyApi,
  delAusAsstntStndrdItemApi, addOrUpdateAusAsstntStndrdItemListApi, getStandardAttributesInfoApi,
  saveStandardAttributesInfoApi, delStandardAttributesInfoApi, getGeneralPropertiesApi
} from "@/api/medicalLibrary/standardAttributes";
import constant from "@/utils/constant";

import asstntStndrdItems from '../../../../common/asstntStndrdItems.vue';


export default {
  components: {
    asstntStndrdItems,
  },
  data() {
    return {
      mobileShowFlag: [
        {
          id: 1,
          label: '否',
          value: '0'
        },
        {
          id: 2,
          label: '是',
          value: '1'
        }
      ],
      titleInfo: '',
      itemCodeFlag: false,
      propertyTypeCheck: '',
      propertyTypeOpt: [
        {
          id: 1,
          label: '自定义属性',
          value: '0'
        },
        {
          id: 2,
          label: '通用属性',
          value: '1'
        }
      ],
      gradedFlagOpt: [
        {
          id: 1,
          label: '是',
          value: '1'
        },
        {
          id: 2,
          label: '否',
          value: '0'
        }
      ],
      propertyListOpt: [],
      commonProperty: "",//标准化体检项配置id
      // 体检项目库数据
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //    子项表格
      tableData: [],
      tableData2: [],
      currentRow: {},

      // 添加项目弹窗
      addProjectVisible: false,
      stndrdItemForm: {
        id: '',
        itemsName: '',
        itemsCode: '',
      },
      projectRules: {
        itemsCode: [
          { required: true, message: '请输入项目代码', trigger: 'blur' }
        ],
        itemsName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
      },
    }
  },
  created() {
    this.getPropertyList();
  },
  methods: {
    propertyTypeClk(val,row){
      row.propertyId = '';
      row.propertyName = '';
      if(val == '0'){
        row.gradedFlag = '0'
      }
    },
    // 获取属性列表
    getPropertyList() {
      getGeneralPropertiesApi({}).then((res) => {
        if (res.resultCode == constant.SUCCESS) this.propertyListOpt = res.data || []
      })
        .catch((err) => {
        });
    },
    // 点击添加项目按钮
    addProject() {
      this.$set(this.stndrdItemForm, 'itemsCode', '')
      this.$set(this.stndrdItemForm, 'itemsName', '')
      this.titleInfo = '新增体检项目'
      this.itemCodeFlag = false;
      this.addProjectVisible = true
    },
    editOrDeleteAction(row) {
      this.stndrdItemForm.id = row.id
      this.$set(this.stndrdItemForm, 'itemsCode', row.itemsCode)
      this.$set(this.stndrdItemForm, 'itemsName', row.itemsName)
      this.titleInfo = '修改体检项目'
      this.itemCodeFlag = true;
      this.addProjectVisible = true;

    },
    queryStandItemTableData(id, itemsCode, isLock, currentRow) {
      this.commonProperty = id;
      this.currentRow = currentRow;
      this.tableData = []
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      this.getListData(this.commonProperty);
    },
    getListData(itemsCode) {
      getStandardAttributesInfoApi({ id: itemsCode }).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          this.tableData = res.data || []
        }
      })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        })
      getAusAsstntHealthPropertyInfoApi({ id: itemsCode }).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          this.tableData2 = res.data || []
        }
      })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        })
    },
    // 点击标准化列表删除按钮
    handleDel(_index, row) {
      this.$confirm(`是否删除此子项目信息?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.id) {
            this.$store.dispatch("loading/CHANGE_LOADING", true);
            delStandardAttributesInfoApi({ id: row.id }).then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.resultCode == constant.SUCCESS) {
                this.tableData.splice(_index, 1);
                this.$message.closeAll()
                this.$message.success('删除成功')
              }
            })
              .catch((err) => {
                this.$store.dispatch("loading/CHANGE_LOADING", false);
              });
          } else {
            this.tableData.splice(_index, 1);
            this.$message.closeAll()
            this.$message.success('删除成功')
          }
        })
        .catch(() => { })
    },
    // 点击标准化新增按钮
    sonAddClick() {
      if(this.commonProperty == undefined || this.commonProperty =='' || this.commonProperty == null){
          this.$message.closeAll()
            this.$message.warning('请选择体检项目!')
            throw new Error('')
      }
      this.tableData.push({
        propertyId: '',
        propertyType: '',
        propertyName: '',
        exampleInfo: '',
        gradedFlag: '',
      })
    },
    // 点击标准化保存接口
    standPropertySaveClick() {
      try {
        var count = 0;
        if(this.commonProperty == undefined || this.commonProperty =='' || this.commonProperty == null){
          this.$message.closeAll()
            this.$message.warning('请选择体检项目!')
            throw new Error('')
        }
        this.tableData.forEach(item => {
          if (!item.propertyType) {
            this.$message.closeAll()
            this.$message.warning('属性分类不能为空!')
            throw new Error('')
          }
          if (item.propertyType == '0') {
            if (!item.propertyName) {
              this.$message.closeAll()
              this.$message.warning('自定义属性名称不能为空!')
              throw new Error('')
            }
          } else if (item.propertyType == '1') {
            if (!item.propertyId) {
              this.$message.closeAll()
              this.$message.warning('通用属性名字不能为空!')
              throw new Error('')
            }
          }
          if (!item.exampleInfo) {
            this.$message.closeAll()
            this.$message.warning('关键字不能为空!')
            throw new Error('')
          }
          if (!item.gradedFlag) {
            this.$message.closeAll()
            this.$message.warning('体检分级标志不能为空!')
            throw new Error('')
          } else {
            if (item.gradedFlag == "1") {
              count++;
            }
          }
          if (count > 1) {
            this.$message.closeAll()
            this.$message.warning('体检分级标志只能配置一个！')
            throw new Error('')
          }
        })

      } catch (error) {
        return
      }
      this.saveStandardAttributesInfo()
    },
    saveStandardAttributesInfo() {
      let params = {
        commonProperty: this.commonProperty,
        ausAsstntStndrdPropertyList: this.tableData
      }
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      saveStandardAttributesInfoApi(params).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          this.$message.closeAll()
          this.$message.success('保存成功')
          this.$refs.projectLibrary.currentId = null
          this.$refs.projectLibrary.filterText = ''
          this.getListData(this.commonProperty);
          this.$refs.projectLibrary.getProjectLibraryList(numbers.indexOf(this.commonProperty))
        }
      })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        })
    },
    // 点击健康个人信息新增按钮
    healthAddClick() {
      if(this.commonProperty == undefined || this.commonProperty =='' || this.commonProperty == null){
          this.$message.closeAll()
            this.$message.warning('请选择体检项目!')
            throw new Error('')
      }
      this.tableData2.push({
        propertyName: '',
        showFlag: '',
      })
    },
    // 点击健康个人信息列表删除按钮
    healthHandleDel(_index, row) {
      this.$confirm(`是否删除此子项目信息?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.id) {
            this.$store.dispatch("loading/CHANGE_LOADING", true);
            delAusAsstntHealthPropertyApi({ id: row.id }).then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.resultCode == constant.SUCCESS) {
                this.tableData2.splice(_index, 1);
                this.$message.closeAll()
                this.$message.success('删除成功')
              }
            })
              .catch((err) => {
                this.$store.dispatch("loading/CHANGE_LOADING", false);
              });
          } else {
            this.tableData2.splice(_index, 1);
            this.$message.closeAll()
            this.$message.success('删除成功')
          }
        })
        .catch(() => { })
    },
    // 点击健康个人信息保存接口
    healthPropertySaveClick() {
      try {
        if(this.commonProperty == undefined || this.commonProperty =='' || this.commonProperty == null){
          this.$message.closeAll()
            this.$message.warning('请选择体检项目!')
            throw new Error('')
        }
        this.tableData2.forEach(item => {
          if (!item.propertyName) {
            this.$message.closeAll()
            this.$message.warning('个人健康信息不能为空!')
            throw new Error('')
          }

          if (!item.showFlag) {
            this.$message.closeAll()
            this.$message.warning('移动端是否显示不能为空!')
            throw new Error('')
          }
        })

      } catch (error) {
        return
      }
      let params = {
        commonProperty: this.commonProperty,
        ausAsstntHealthPropertyList: this.tableData2
      }
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      saveAusAsstntHealthPropertyInfoApi(params).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          this.$message.closeAll()
          this.$message.success('保存成功')
          this.$refs.projectLibrary.currentId = null
          this.$refs.projectLibrary.filterText = ''
          this.getListData(this.commonProperty);
          this.$refs.projectLibrary.getProjectLibraryList(numbers.indexOf(this.commonProperty))
        }
      })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        })
    },
    isNameInArrayUnique(arr) {
      const seenNames = new Set();
      for (const obj of arr) {
        const gradedFlag = obj.gradedFlag;

        if (seenNames.has(gradedFlag)) {
          return false; // 重复的gradedFlag
        }
        seenNames.add(gradedFlag);
      }
      return true; // 所有gradedFlag都是唯一的
    },

    // 弹窗按钮
    // 点击确认
    stndrdItemSave() {
      this.$refs.stndrdItemForm.validate((valid) => {
        if (valid) {
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          addOrUpdateAusAsstntStndrdItemListApi(this.stndrdItemForm).then(res => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
            if (res.resultCode == constant.SUCCESS) {
              this.$message.closeAll()
              this.$message.success('新增成功')
              this.projectReset()
              setTimeout(() => {
                this.$refs.projectLibrary.currentId = null
                this.$refs.projectLibrary.filterText = ''
                this.$refs.projectLibrary.getProjectLibraryList()
              }, 200)
            }
          })
            .catch((err) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            })
        }
      });
    },
    //删除
    stndrdItemDelete(row) {
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      delAusAsstntStndrdItemApi({ id: row.id }).then(res => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          this.$message.closeAll()
          this.$message.success('删除成功')
          this.projectReset()
          setTimeout(() => {
            this.$refs.projectLibrary.currentId = null
            this.$refs.projectLibrary.filterText = ''
            this.$refs.projectLibrary.getProjectLibraryList()
          }, 200)
        }
      })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        })
    },
    // 点击取消
    projectReset() {
      this.addProjectVisible = false
      this.stndrdItemForm = {
        propertyType: '',
        propertyName: '',
        propertyId: '',
        exampleInfo: '',
        gradedFlag: '',
      }
    }
  },
}

</script>

<style lang="less" scoped>
.right-title {
  background: #f8f8f8;
  padding: 10px 25px;
  margin-left: 15px;
  position: relative;
}

.right-title::before {
  content: '';
  position: absolute;
  top: 11px;
  left: 15px;
  width: 3px;
  height: 18px;
  background: #f76767;
}

.top_box {
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid rgb(241, 238, 238);
  margin-bottom: 15px;
}

.top_box h1 {
  font-weight: 600;
  margin-left: 15px;
}

.left_box {
  width: 400px;
  border: 1px solid #e3dddd;
}

.right_box {
  width: calc(100% - 350px);
  /* border: 1px solid #e3dddd; */
}

/deep/ .filter-tree {
  max-height: calc(100vh - 340px);
  overflow: auto;
}
</style>